﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base.Doc;
using UFIDA.U9.Complete.RCVRpt;
using UFIDA.U9.Cust.YYD.PlugBE.Dtos;
using UFIDA.U9.Cust.YYD.PlugBE.Public;
using UFIDA.U9.MO.Complete;
using UFIDA.U9.MO.MO;
using UFIDA.U9.PM.Rcv;
using UFSoft.UBF.Business;

namespace UFIDA.U9.Cust.YYD.PlugBE.MOP
{
    public class AfterUpdating : UFSoft.UBF.Eventing.IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            var holder = key.GetEntity() as UFIDA.U9.MO.MO.MO;
            if (holder == null)
                return;
            #endregion
            //开工
            if (holder.OriginalData.DocState == MO.Enums.MOStateEnum.Approved && holder.DocState == MO.Enums.MOStateEnum.Released /*&& MOIsChange(holder.OriginalData, holder)*/)
            {
                HttpHelper httpHelper = new HttpHelper();
                JsonConfig config = new JsonConfig();
                httpHelper.GetMESToken();
                var URL = config.SelectToken("MES.URL") + "/mes_api/bzcomponent/u9c_data_download/MFGOrderDataSave";
                MESMODTO dto = new MESMODTO();
                Maindata maindata = new Maindata();
                dto.mainData = maindata;
                maindata.mfgOrderCode = holder.DocNo;
                maindata.material = holder.ItemCode;
                //maindata.processRoute = holder.Routing;
                maindata.pQty = holder.ProductQty;
                maindata.unit = holder.ProductUOM.Code;
                maindata.orderTime = holder.BusinessDate.ToString("yyyy-MM-dd");
                maindata.planTime = holder.StartDate.ToString("yyyy-MM-dd");

                //if (holder.DocType.BusinessType != BusinessTypeEnum.MO_StandardProduction)
                //    maindata.orderType = "Standard";
                //if (holder.DocType.BusinessType != BusinessTypeEnum.MO_ReworkProduction)
                //    maindata.orderType = "Rework";
                maindata.orderType = holder.DocType.Code;
                maindata.orderTypeDesc = holder.DocType.Name;

                //var cpdoctype = RcvRptDocType.Finder.Find($"BusinessType = {holder.BusinessType.Value} and Org.ID = {holder.Org.ID}");
                var rcvRptDocType = "";
                if(holder.DocType.Name.Contains("-"))
                    rcvRptDocType = holder.DocType.Name.Split('-')[1];
                maindata.finishedInventoryType = rcvRptDocType;

                maindata.workCenter = holder.Department.Code;
                maindata.factory = holder.Org.Code;
                maindata.warehouse = holder.SCVWh.Code;
                maindata.planBeginDate = holder.StartDate.ToString("yyyy-MM-dd");
                maindata.planEndDate = holder.CompleteDate.ToString("yyyy-MM-dd");
                maindata.fromBill = holder.SrcDoc.SrcDocNo;
                maindata.fromDomain = holder.SrcDoc.SrcDocType;
                maindata.area = holder.Department?.Code?.Substring(0, 4)??"";

                foreach (var pick in holder.MOPickLists)
                {
                    Mfgmaterialdata pickDto = new Mfgmaterialdata();
                    pickDto.material = pick.ItemCode;
                    pickDto.totalQty = pick.ActualReqQty;
                    pickDto.unit = pick.IssueUOM.Code;
                    pickDto.warehouse = pick.SupplyWh.Code;
                    pickDto.seq = pick.DocLineNO;
                    pickDto.excessCollarRatio = pick.StandardMaterialScale;
                    dto.MFGMaterialData.Add(pickDto);
                }

                foreach (var output in holder.MOOutputs)
                {
                    if (output.OutputType != CBO.MFG.Enums.ProductTypeEnum.Component)
                    {
                        JointProductData joinDto = new JointProductData();
                        joinDto.material = output.Item.Code;
                        joinDto.planQty = output.PlanOutputQty;
                        joinDto.unit = output.ProductUOM.Code;
                        if (output.OutputType != CBO.MFG.Enums.ProductTypeEnum.ByProduct)
                            joinDto.jointProductType = "ByProducts";
                        if (output.OutputType != CBO.MFG.Enums.ProductTypeEnum.CoProduct)
                            joinDto.jointProductType = "CoProducts";

                        dto.JointProductData.Add(joinDto);
                    }
                }

                var json = JsonConvert.SerializeObject(dto);
                //LogManager.WriteLog(httpHelper.Content, "Test");
                //var result = JsonConvert.DeserializeObject<MESReturnDTO>(httpHelper.Request("PUT"));
                httpHelper.URL = URL;
                httpHelper.Content = json;
                //var result = JsonConvert.DeserializeObject<MESReturnDTO>(httpHelper.HttpPosts("PUT"));
                var result = JObject.Parse(httpHelper.HttpPosts("PUT"));
                if (result["code"].ToString() != "0")
                {
                    throw new Exception("同步MES失败。报错信息:" + result["message"].ToString());
                }

            }
        }
        public bool MOIsChange(UFIDA.U9.MO.MO.MO.EntityOriginal a, UFIDA.U9.MO.MO.MO b)
        {
            return a?.ProductQty != b?.ProductQty ||
                PickIsChange(a.MOPickLists, b.MOPickLists.Cast<MOPickList>().ToList());
        }
        public bool PickIsChange(List<MOPickList> a, List<MOPickList> b)
        {
            for (int i = 0; i < a.Count; i++)
            {
                if (a[i].ItemMaster.ID != b[i].ItemMaster.ID ||
                    a[i].ActualReqQty != b[i].ActualReqQty)
                {
                    return true;
                }
            }
            return false;
        }

    }
}
